
#if	!defined( __20081117_DEF_LINUX_LOCK_H__ )
#define	__20081117_DEF_LINUX_LOCK_H__

#include	<errno.h>
#include	<pthread.h>

namespace PCE_Lib {
namespace CEnv_Def {
namespace PCE_Lib_CurrentCEnvironment {
namespace Tools {

class Lock
{
public:
	bool GetLock( void ) throw()
	{
		return 0 == pthread_mutex_lock( & m_Mutex );
	}
	bool ReleaseLock( void ) throw()
	{
		return 0 == pthread_mutex_unlock( & m_Mutex );
	}
public:
	/**
	 *	1. Free mutex; 2. Create a new
	 */
	bool Alloc( void ) throw()
	{
		switch( pthread_mutex_destroy( & m_Mutex ) ) {
		case 0: case EINVAL:
			return 0 == pthread_mutex_init( & m_Mutex,
				Null< const pthread_mutexattr_t * >() );
		case EBUSY: default:
			return false;
		}
	}
	/**
	 *	If retrun true, succeed; if return false, do not free
	 */
	bool Free( void ) throw()
	{
		return 0 == pthread_mutex_destroy( & m_Mutex );
	}
public:
	Lock( void ) throw() : m_Mutex() {}
	~Lock( void ) throw() { Free(); }	// may not be freeed, if other thread holds the lock
protected:
	pthread_mutex_t		m_Mutex;
};

}	// Tools
}	// PCE_Lib_CurrentCEnvironment
}	// CEnv_Def
}	// PCE_Lib

#endif	// __20081117_DEF_LINUX_LOCK_H__
